<script setup lang="ts">
import { ElMessageBox } from 'element-plus'

import GameBoard from './components/GameBoard.vue'
import MobileControls from './components/MobileControls.vue'
import { useTetris } from './hooks/useTetris'
import type { Direction } from './types'

// 路由
const router = useRouter()

// 游戏状态
const running = ref(false)
const paused = ref(false)
const timer = ref<number | null>(null)
const started = ref(false) // 控制是否显示游戏面板和得分

// 速度（ms），简单-800，中等-500，困难-300
const speed = ref(500)

async function handleGameOver() {
  running.value = false
  if (timer.value)
    clearInterval(timer.value)

  await ElMessageBox.alert(`游戏结束！总得分：${score.value}`, '提示', {
    confirmButtonText: '重新开始',
    cancelButtonText: '返回首页',
    showCancelButton: true,
    type: 'warning',
  }).then(() => {
    startGame(speed.value)
  }).catch(() => {
    router.push('/')
  })
}

const { score, moveBlock, tick, getBoardWithBlock, reset } = useTetris(handleGameOver)

const displayBoard = computed(() => getBoardWithBlock())

// 开始游戏，接收速度参数
function startGame(gameSpeed: number) {
  if (running.value)
    return

  running.value = true
  paused.value = false
  started.value = true // 点击开始，显示游戏区域
  reset()
  speed.value = gameSpeed

  if (timer.value)
    clearInterval(timer.value)
  timer.value = setInterval(() => {
    if (!paused.value)
      tick()
  }, speed.value) as any
}

function pauseGame() {
  if (!running.value)
    return
  paused.value = !paused.value
}

function resetGame() {
  running.value = false
  paused.value = false
  if (timer.value)
    clearInterval(timer.value)
  reset()
  // 如果想重置时隐藏游戏区域，取消下面注释：
  // started.value = false
}

function handleMove(direction: Direction) {
  moveBlock(direction)
}

function onKeyDown(e: KeyboardEvent) {
  if (!running.value)
    return
  switch (e.key.toLowerCase()) {
    case 'a':
    case 'arrowleft':
      handleMove('left')
      break
    case 'd':
    case 'arrowright':
      handleMove('right')
      break
    case 's':
    case 'arrowdown':
      handleMove('down')
      break
    case 'w':
    case 'arrowup':
      handleMove('rotate')
      break
  }
}

onMounted(() => {
  window.addEventListener('keydown', onKeyDown)
})

onBeforeUnmount(() => {
  if (timer.value)
    clearInterval(timer.value)
  window.removeEventListener('keydown', onKeyDown)
})

// 选择难度
const difficulty = ref('medium') // 默认中等

// 绑定难度与速度映射
const difficultySpeedMap = {
  easy: 800,
  medium: 500,
  hard: 300,
}

function onSelectDifficulty(level: string) {
  difficulty.value = level
  if (running.value) {
    startGame(difficultySpeedMap[level])
  }
}
function handleGoHome() {
  router.push('/')
}
</script>

<template>
  <div class="tetris-container">
    <el-card class="tetris-card">
      <div class="game-header">
        <h2>俄罗斯方块</h2>
        <el-radio-group v-if="!started" v-model="difficulty" :disabled="running" @change="onSelectDifficulty">
          <el-radio-button label="easy">
            简单
          </el-radio-button>
          <el-radio-button label="medium">
            中等
          </el-radio-button>
          <el-radio-button label="hard">
            困难
          </el-radio-button>
        </el-radio-group>

        <el-button-group style="margin-top: 10px;">
          <el-button :disabled="running" @click="startGame(difficultySpeedMap[difficulty])">
            开始
          </el-button>
          <el-button :disabled="!running" @click="pauseGame">
            {{ paused ? '继续' : '暂停' }}
          </el-button>
          <el-button @click="resetGame">
            重置
          </el-button>
        </el-button-group>
        <el-button @click="handleGoHome">
          返回首页
        </el-button>
      </div>

      <template v-if="started">
        <p class="score">
          得分：{{ score }}
        </p>
        <GameBoard :board="displayBoard" />
        <MobileControls style="margin-top: 10px;" @move="handleMove" />
      </template>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
$tetris-bg: #1e1e2f;
$tetris-primary: #29b6f6;
$tetris-text: #f0f4f8;

.tetris-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
  padding: 0 20px 20px;
  :deep(.el-card) {
    padding: 0 10px;
  }
}

.tetris-card {
  width: 100%;
  max-width: 360px;
  background-color: rgba(30, 30, 47, 0.95);
  border-radius: 16px;
  box-shadow: 0 0 25px rgba(41, 182, 246, 0.7);

  .game-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 15px;

    h2 {
      color: $tetris-primary;
      margin-bottom: 10px;
    }

    .el-button-group {
      margin-bottom: 10px;
    }
  }

  .score {
    color: $tetris-text;
    font-size: 1.2em;
    font-weight: bold;
    margin-bottom: 10px;
    text-align: center;
  }
}
</style>
